import JSEncrypt from 'jsencrypt'
import qs from 'qs'

export function antPathMatch(antPattern, path) {
  // 将通配符转换为正则表达式
  let regex =
    antPattern
      .replace(/(\*\*)/g, '(?:.*\\/)?') // 处理**，匹配任意多级目录
      .replace(/(\*)/g, '[^\\/]*') // 处理*，匹配任意非路径分隔符字符序列
      .replace(/\//g, '\\\\/') // 转义路径分隔符
      .replace(/\./g, '\\.') // 转义点号，以正确匹配如".txt"这样的文件扩展名
      // 确保模式以路径分隔符开始和结束，以精确匹配整个路径，而不是作为子串匹配
      .replace(/^\/|\/$/g, '') + '$'

  // 使用新生成的正则表达式测试路径是否匹配
  return new RegExp('^' + regex).test(path)
}

export function setToken(token) {
  localStorage.setItem('token', token)
}

export function getToken() {
  return localStorage.getItem('token')
}

export function removeToken() {
  return localStorage.removeItem('token')
}

export function encryptPassword(key, rwaPassword) {
  var encrypt = new JSEncrypt()
  encrypt.setPublicKey(key)
  return encrypt.encrypt(rwaPassword)
}

export function groupBy(arr, key) {
  return arr.reduce((groups, item) => {
    const groupKey = item[key]
    if (!groups[groupKey]) {
      groups[groupKey] = []
    }
    groups[groupKey].push(item)
    return groups
  }, {})
}

export function setDefer(data) {
  if (!data) {
    return
  }
  let arr = data
  if (!Array.isArray(data)) {
    arr = data.children
  }
  for (let i = 0; i < arr.length; i++) {
    arr[i].defer = arr[i].level == 1 || arr[i].level == 2
  }
}

export function getSystemId(){
  const params = qs.parse(window.location.search.split('?')[1]);
  if(params.systemId && localStorage.getItem('systemId') == null){
    localStorage.setItem('systemId', params.systemId);
  }
  return params.systemId || localStorage.getItem('systemId') || 100;
}

export function getPermissions(menus){
  if(menus == null || menus.length == 0){
    return [];
  }
  let permissions = [];
  menus.map(m => {
    if(m.type === 3 && m.permission){
      permissions.push(m.permission);
    }
    if(m.children && m.children.length){
      permissions.push(...getPermissions(m.children));
    }
  });
  return permissions;
}